package com.xhui.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.xhui.reggie.common.BaseContext;
import com.xhui.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;



/**
 * 检查用户是否进行登录
 */
// urlPatterns: 拦截符合urlPatterns规则的请求
// case: urlPatterns="/*", 就会拦截到所有以 localhost:port/ 开头的路径
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{

    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestUrl = request.getRequestURL().toString();
        System.out.println("request.getRequestURL().toString() = " + requestUrl);
        //1. 获取本次请求的URI
        String requestUri = request.getRequestURI();
        System.out.println("requestUri = " + requestUri);
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        
        //log.info("存在请求 {}", requestUri);

        //  "/backend/**" and "/front/**" 都是静态资源访问，
        //
        String[] allowedUrls = new String[]{
                "/front/**",
                "/backend/**",
                "/employee/login",
                // "employee/logout",个人感觉需要注释掉
                // "/common/**",   // 不登录下仍能进行上传文件
                "/user/sendMsg", // 移动端发送短信
                "/user/login"    // 移动端登录
        };

        String[] frontUrls = new String[]{

        };

        String[] backendUrls = new String[]{

        };


        //2. 请求资源合法放行
        if (check(allowedUrls, requestUri)){
            //log.info("以上请求存在允许放行资源内");
            //访问的是合法允许资源，放行
            filterChain.doFilter(request, response);
            return ;
        }

        String requestedSessionId = request.getRequestedSessionId();
        System.out.println("requestedSessionId = " + requestedSessionId);

        HttpSession session = request.getSession();

        // 3-1 判断员工登录状态, 若处于已登录状态且想访问任何请求无需拦截，放行
        if (session.getAttribute("employee") != null){
          log.info("用户已登录,id为{}", session.getAttribute("employee"));

            // 给线程本地ThreadLocal设置当前登录用户的id,便于其他类使用
            Long empId = (Long) session.getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request, response);
            // 成功访问到资源，不需再修改response，直接结束方法return ;
            return ;
        }/*else{
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }*/

        // 后台已登录，不能访问前台资源

        // user != null employee == null
        // 3-2 判断用户登录状态, 若处于已登录状态且想访问任何请求无需拦截，放行
        if (session.getAttribute("user") != null){
          log.info("用户已登录,id为{}", session.getAttribute("user"));

            // 给线程本地ThreadLocal设置当前登录用户的id,便于其他类使用
            Long userId = (Long) session.getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            // 成功访问到资源，不需再修改response，直接结束方法 return ;
            return ;
        }

        // 4. 如果未登录，则返回未登录结果，通过输出流向前端响应数据
//        log.info("用户未登录");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param allowedUrls
     * @param requestURI
     * @return
     */
    public boolean check(String[] allowedUrls, String requestURI)  {
        for (String url : allowedUrls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
